<script setup lang="ts">
import HeaderNav from '@/components/layout/HeaderNav.vue'
import AdminHeaderNav from '@/components/layout/AdminHeaderNav.vue'
import SearchBar from '@/components/layout/SearchBar.vue'
import FooterNav from '@/components/layout/FooterNav.vue'
import Home from '@/components/layout/Home.vue'
import KillSection from '@/components/home/KillSection.vue'
import GuessYouLike from '@/components/layout/GuessYouLike.vue'
import Cart from '@/views/cart/Cart.vue'
import AIDialog from '@/components/ai/AIDialog.vue'
import { useUserStore } from '../stores/user'
import { computed, ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { getUserInfoService } from '../api/user'
const userStore = useUserStore()
const route = useRoute()

// AI对话框显示状态
const isAIDialogVisible = ref(false)

// 根据用户类型决定显示哪个导航栏（role===3 为管理员）
const isAdmin = computed(() => userStore.isAdmin)

// 判断当前是否为购物车页面
const isCartPage = computed(() => route.path === '/cart')

// 切换AI对话框显示/隐藏
const toggleAIDialog = () => {
  isAIDialogVisible.value = !isAIDialogVisible.value
}

import { useTokenStore } from '../stores/token'
// 在组件挂载时获取用户信息
onMounted(async () => {
  const tokenStore = useTokenStore()
  // 只有当用户有token时才调用接口获取用户信息
  if (tokenStore.token) {
    try {
      const response = await getUserInfoService()
      if (response && response.data) {
        const userInfo = response.data
        // 保存用户信息到pinia store（后端已改为 role 字段）
        userStore.setUsername(userInfo.username, userInfo.id, Number(userInfo.role))
        // 保存头像地址到pinia store
        if (userInfo.userPic) {
          userStore.setAvatar(userInfo.userPic)
        }
      }
    } catch (error) {
      console.log('获取用户信息失败:', error)
      // 失败时不做处理，保持默认状态
    }
  }
})
</script>

<template>
  <div class="layout-container">
    <div class="page-wrap">
      <!-- 根据用户类型显示不同的导航栏 -->
      <AdminHeaderNav v-if="isAdmin" />
      <HeaderNav v-else />
      <SearchBar :on-ai-search="toggleAIDialog" />
      <!-- 主要内容区域 -->
      <main class="main-content">
        <!-- 根据路由显示不同内容 -->
        <Cart v-if="isCartPage" />
        <template v-else>
          <Home />
          <KillSection />
          <GuessYouLike />
        </template>
      </main>
      <slot />
    </div>
      <AIDialog :visible="isAIDialogVisible" />

    <FooterNav />
  </div>
</template>

<style scoped lang="scss">
.layout-container {
  min-height: 90vh;
  display: flex;
  flex-direction: column;
}

/* 页面主体左右留白，不影响顶部导航与页脚 */
.page-wrap {
  padding: 0 2.5rem;
}

/* 缩小顶部导航栏和搜索栏之间的间距 */
.page-wrap .bkd-search-bar {
  margin-top: -1.3125rem; /* 使用负边距减少间距 */
}

.main-content {
  flex: 1;
  min-height: 12.5rem;
  padding: 0.1875rem 0;
}
</style>